//! @Author: DengLibin 
//! @Date:  2022-04-21 09:21:26
//! @Description: 
use actix_web::{
    ResponseError, HttpResponse, body::BoxBody,
    http::{header::ContentType},
};

use derive_more::Display;
use rand::{
    distributions::{Distribution, Standard}, Rng,
};
/// 自定义错误
#[derive(Debug, Display)]
pub enum CustomError {
    #[display(fmt = "Custom Error 1")]
    CustomOne,
    #[display(fmt = "Custom Error 2")]
    CustomTwo,
    #[display(fmt = "Custom Error 3")]
    CustomThree,
    #[display(fmt = "Custom Error 4")]
    CustomFour,
}

impl Distribution<CustomError> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> CustomError {
        match rng.gen_range(0..4) {
            0 => CustomError::CustomOne,
            1 => CustomError::CustomTwo,
            2 => CustomError::CustomThree,
            _ => CustomError::CustomFour,
        }
    }
}

/// 实现 ResponseError
impl ResponseError for CustomError {
    fn error_response(&self) -> HttpResponse<BoxBody> {
        match self {
            CustomError::CustomOne => {
                HttpResponse::Forbidden().content_type(ContentType::plaintext()).body("禁止访问")
            }

            CustomError::CustomTwo => {
                HttpResponse::Unauthorized().content_type(ContentType::plaintext()).body("未认证")
            }

            CustomError::CustomThree => {
                HttpResponse::InternalServerError().content_type(ContentType::plaintext()).body("服务端内部错误")
            }

            _ => {
               // HttpResponse::BadRequest().finish()
                HttpResponse::BadRequest().content_type(ContentType::plaintext()).body("错误的请求")
            }
        }
    }
}